package com.hp.goods_details_service.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class GoodsDetailHTMLService {

    //静态文件保存的目录
    public static final String PATH = "D:\\nginx-1.12.2\\html\\goods-details\\";

    //线程池
    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    //模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 页面静态化
     * @param spuId
     */
    public void createHtml(Map<String,Object> map ,Long spuId){
        threadPool.execute(() -> {
            try {
                //创建页面上下文
                Context context = new Context();
                //存入数据
                context.setVariables(map);
                File path = new File(PATH);
                if(!path.exists()){
                    path.mkdirs();
                }
                //创建文件流
                PrintWriter printWriter = new PrintWriter(PATH + spuId + ".html");
                //静态化 item是页面模板的名称，context上下文
                templateEngine.process("item",context,printWriter);
            } catch (Exception e) {
                log.error("页面静态化出现异常",e);
            }
        });
    }
}
